<template>
  <div v-loading="showSpin">
    <el-card class="search-card">
      <div slot="header" class="clearfix">
        <span>SPU下增加SKU</span>
      </div>
      <div class="header-content">
        <el-row :gutter="5">
          <el-col :span="12">
            <el-card class="search-card" shadow="never">
              <div slot="header" class="clearfix">
                <span>SPU信息</span>
              </div>
              <el-form
                ref="form"
                label-position="right"
                :model="skuInfo"
                label-width="150px"
              >
                <el-form-item class="spu-input" label="SPU编码:">
                  <el-input readonly v-model="skuInfo.spuNo"
                    ><el-button @click="handleShowSpuDialog" slot="append" icon="el-icon-search"></el-button
                  ></el-input>
                </el-form-item>
                <el-form-item label="商品名称:">
                  <span>{{skuInfo.productNameFinal}}</span>
                </el-form-item>
                <el-form-item label="品牌:">
                  <span>{{skuInfo.brandName}}</span>
                </el-form-item>
                <el-form-item label="加价类型:">
                  <span>{{skuInfo.addPriceTypeStr}}</span>
                </el-form-item>
                <el-form-item label="是否采购多计量:">
                  <span>{{skuInfo.isPurchaseMultiUnitStr}}</span>
                </el-form-item>
                <el-form-item label="是否销售多计量:">
                  <span>{{skuInfo.isSaleMultiUnitStr}}</span>
                </el-form-item>
                <el-form-item label="主计量单位:">
                  <span>{{skuInfo.mainUnitName}}</span>
                </el-form-item>
                <el-form-item label="辅计量单位:">
                  <span>{{skuInfo.assistUnitName}}</span>
                </el-form-item>
              </el-form>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="search-card" shadow="never">
              <div slot="header" class="clearfix">
                <span>SPU下已有SKU展示</span>
              </div>
              <sku-table
                :tableHeight="395"
                :columns="columns"
                :dataSource="skuList"
              />
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-card>
    <div class="sale_attr" v-show="saleAttrViseble()">
      <sale-attr
        :specList="specList"
        :categoryUuid="categoryUuid"
        @generateSkuList="generateSkuList"
      />
    </div>
    <select-spu-dialog
      :dialogVisible="spuDialogVisible"
      @hide-handler="handleCloseSpuDialog"
    />
    <el-backtop target="#app .i-layout-content-main">
      <i class="el-icon-top"></i>
    </el-backtop>
  </div>
</template>
<script>
import SkuTable from '@/components/skusTable';
import SaleAttr from './components/saleAttribute';
import SelectSpuDialog from './components/SelectSpuDialog';
import { ApiRequest } from '@api/basePage';
import { isResponseSuccess } from '@/utils/bizUtils';
// import { getBtnsId } from '@/libs/btnsPermission';

export default {
  components: {
    SkuTable,
    SaleAttr,
    SelectSpuDialog
  },
  data () {
    return {
      spuDialogVisible: false,
      showSpin: false,
      productUuid: '',
      hasBarcode: 2, // 在所选择的spu下新增sku时，是否需要填写商品条形码，1是，2否，默认值为2否
      skuInfo: {
        spuNo: '',
        productNameFinal: '',
        brandName: '',
        addPriceTypeStr: '',
        isPurchaseMultiUnitStr: '',
        isSaleMultiUnitStr: '',
        mainUnitName: '',
        assistUnitName: '',
      },
      columns: [
        {
          title: 'SKU编码',
          key: 'skuNo'
        },
        {
          title: '规格',
          key: 'specDetailStr'
        }
      ],
      skuList: [],
      specList: [],
      categoryUuid: ''
    };
  },
  methods: {
    // SPU基本信息查询
    querySpuDetailAction (productUuid) {
      ApiRequest(`/sysback/product/spuinfo/getProductMainDetailByUuid?productUuid=${productUuid}`, 'post', {}, false)
        .then((res) => {
          if (isResponseSuccess(res)) {
            this.skuInfo = res.retData;
            if (res.retData && res.retData.categoryUuid) {
              this.categoryUuid = res.retData.categoryUuid;
              this.querySaleAttrAction(res.retData.categoryUuid)
            }
          }
        })
        .catch(() => {
        });
    },
    // SPU已关联sku查询
    querySkuListAction (productUuid) {
      this.showSpin = true;
      ApiRequest(`/sysback/product/spuinfo/getSkuListByProductUuid?productUuid=${productUuid}`, 'post', {}, false)
        .then((res) => {
          this.showSpin = false;
          if (isResponseSuccess(res)) {
            this.skuList = res.retData;
          }
        })
        .catch(() => {
          this.showSpin = false;
        });
    },
    // 销售属性
    querySaleAttrAction (categoryUuid) {
      // this.showSpin = true;
      ApiRequest(`/sysback/product/addSku/basicInfo/getSpecAttrsByCategoryUuid?categoryUuid=${categoryUuid}`, 'post', {}, false)
        .then((res) => {
          this.showSpin = false;
          if (isResponseSuccess(res)) {
            this.specList = res.retData;
          } else {
            this.specList = [];
          }
        })
        .catch(() => {
          this.showSpin = false;
        });
    },
    // 生成代码
    generateSkuCodeAction (skuList) {
      const data = {
        productUuid: this.productUuid,
        skuList,
      }
      // 校验---所选品牌需要填写商品条形码的话，需要校验填写销售属性时是否填写商品条形码
      if (skuList && skuList.length > 0 && this.hasBarcode && this.hasBarcode == 1) {
        for (let index = 0; index <skuList.length; index++) {
          var barcode = skuList[index].barcode;
          if (!barcode) {
            this.$message.error('请填写商品条形码')
            return;
          }
          if (barcode.length > 300) {
            this.$message.error('商品条形码字符长度不能大于300')
            return;
          }
        }
      }
      this.showSpin = true;
      ApiRequest(`/sysback/product/addSku/basicInfo/generateSkuCode`, 'post', data, false)
        .then((res) => {
          this.showSpin = false;
          if (isResponseSuccess(res)) {
            this.$message.success('生成代码成功')
            this.$router.go(-1);
          }
        })
        .catch(() => {
          this.showSpin = false;
        });
    },
    // 笛卡尔集合
    generateSkuList (data) {
      const { skuList, attributesSkuList } = data;
      // 过滤已有sku规格值集合
      let skuSpecList = this.skuList.map((item) => {
        return item.specDetailStr.replace(/[ ]/g, '')
      })
      // 过滤已勾选规格值集合
      let hasSelectAttrList = attributesSkuList.map((item) => {
        return item.valueName.replace(/[ ]/g, '');
      })
      // 过滤已有规格和当前选择的规格重复项
      let repeatAttrList = skuSpecList.filter((item) => hasSelectAttrList.includes(item));
      if (repeatAttrList.length > 0) {
        return this.$alert(`<p>以下规格重复不能添加，请核实数据情况:</p><p>${repeatAttrList}</p>`, '提示', {
          type: 'warning',
          dangerouslyUseHTMLString: true
        })
      }
      this.generateSkuCodeAction(skuList)
    },
    handleShowSpuDialog () {
      this.spuDialogVisible = true;
    },
    handleCloseSpuDialog (row) {
      if (!row) {
        this.spuDialogVisible = false;
        return;
      }
      const { productUuid = '', hasBarcode = 2 } = row;
      if (productUuid) {
        this.productUuid = productUuid;
        this.hasBarcode = hasBarcode;
        this.querySpuDetailAction(productUuid)
        this.querySkuListAction(productUuid)
      }
      this.spuDialogVisible = false;
    },
    saleAttrViseble () {
      return this.specList && this.specList.length > 0;
    }
  }
};
</script>
<style lang="less" scoped>
.spu-input {
  width: 300px;
}
</style>
